#define _CRT_SECURE_NO_WARNINGS 1
#include "Heap.h"

void HeapSort(HeapDataType* data, int n)
{
	for (int i = (n - 1 - 1) / 2; i >= 0; i--)
	{
		AdjustDown(data, n, i);
	}

	int end = n - 1;
	while (end)
	{
		Swap(&data[0], &data[end]);
		AdjustDown(data, end, 0);
		end--;
	}

	for (int i = 0; i < n; i++)
	{
		printf("%d ", data[i]);
	}

}

void CreateNData()
{
	int n = 10000;
	srand((unsigned int)time(NULL));
	const char* str = "data.txt";
	FILE* pf = fopen(str, "w");
	if (pf == NULL)
	{
		perror("fopen error");
		return;
	}
	
	for (int i = 0; i < n; i++)
	{
		int x = rand() % 10000;
		fprintf(pf, "%d\n", x);
	}

	fclose(pf);

}

void TopKPrint(const char* file, int k)
{
	int* topk = (int*)malloc(sizeof(int) * 10);
	if (topk == NULL)
	{
		perror("malloc fail");
		return;
	}

	FILE* pf = fopen(file, "r");
	if (pf == NULL)
	{
		perror("fopen error");
		return;
	}

	for (int i = 0; i < k; i++)
	{
		fscanf(pf, "%d", &topk[i]);
	}

	for (int i = (k - 1 - 1) / 2; i >= 0; i--)
	{
		AdjustDown(topk, k, i);
	}

	int val = 0;
	int ret = fscanf(pf, "%d", &val);
	while (ret != EOF)
	{
		if (val > topk[0])
		{
			topk[0] = val;
			AdjustDown(topk, k, 0);
		}

		ret = fscanf(pf, "%d", &val);
	}

	for (int i = 0; i < k; i++)
	{
		printf("%d ",topk[i]);
	}

	free(topk);
	fclose(pf);
}

int main()
{
	//HP hp;
	//HeapInit(&hp);

	//HeapPush(&hp, 0);
	//HeapPush(&hp, 4);
	//HeapPush(&hp, 3);
	//HeapPush(&hp, 6);
	//HeapPush(&hp, 8);
	//HeapPush(&hp, 1);
	//HeapPush(&hp, 9);
	//HeapPush(&hp, 7);
	//HeapPush(&hp, 2);
	//HeapPush(&hp, 5);

	//while (!HeapEmpty(&hp))
	//{
	//	printf("%d ", HeapTop(&hp));
	//	HeapPop(&hp);
	//}

	//printf("\n");

	// int data[] = { 1,6,0,3,5,2,8,7,9,4 };
	// HeapSort(data, 10);

	
	// CreateNData();
	TopKPrint("data.txt", 10);
	return 0;
}